#include "plugin_controller.h"
#include "plugin_enumerator.h"
#include "common/print_plugin.h"

CPluginController::CPluginController()
{
}

CPluginController::~CPluginController()
{
}

int CPluginController::InitPlugin()
{
    CPluginEnumerator plugin_enumerator;
    vector<string> plugin_names;
    if (!plugin_enumerator.FindPlugins(plugin_names))
    {
        return -1;
    }
    for (auto& plugin_name : plugin_names)
    {
        typedef void* (*CREATE_OBJ)();
        CREATE_OBJ create_obj_fun = NULL;
        IPlugin* plugin = NULL;

        HINSTANCE hinstance = LoadLibrary(plugin_name.c_str());
        if (hinstance != NULL)
        {
            create_obj_fun = (CREATE_OBJ)GetProcAddress(hinstance, "create_obj");
            if (create_obj_fun == NULL)
            {
                return -2;
            }
            plugin = (IPlugin*)create_obj_fun();
            if (plugin == NULL)
            {
                return -3;
            }
            m_lib_handles.push_back(hinstance);
            m_plugins.push_back(plugin);
        }
    }
    return 0;
}

void CPluginController::UnInitPlugin()
{
    for (auto& plugin_inst : m_lib_handles)
    {
        FreeLibrary(plugin_inst);
    }
}

int CPluginController::ProcessRequest(int id)
{
    for (auto& plugin : m_plugins)
    {
        if (id == plugin->GetID())
        {
            IPrintPlugin* print_plugin = (IPrintPlugin*)plugin;
            print_plugin->Print();
        }
    }
    return 0;
}

void CPluginController::ProcessHelp()
{
    for (auto& plugin : m_plugins)
    {
        IPrintPlugin* print_plugin = (IPrintPlugin*)plugin;
        print_plugin->Help();
    }
}
